//
//  TimerDownImage.m
//  NaRiLSVMT
//
//  Created by zhangmeng on 14-9-9.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "TimerDownImage.h"
#import "FileManager.h"
#import "Network_Operation.h"
#define  PATH [NSString stringWithFormat:@"%@/downimage/",[FileManager getLibraryDirectory]]
#define ARRMAX 40
@implementation TimerDownImage
+ (id)sharedInstance
{
    static TimerDownImage *singleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton = [[[self class] alloc] init];
    });
    return singleton;
}
-(void)stratTimerDownImage
{
    //定时器
    downimageTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
    dispatch_source_set_timer(downimageTimer, DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC,0.0);
    dispatch_source_set_event_handler(downimageTimer, ^{
        //下载数据
        [self getUrlImage:self.templeted];
        
        //下载缩略图
        [self getUrlThumbImage:self.templeted];
    });
    dispatch_resume(downimageTimer);
}
-(void)stopTimerDownImage
{
    dispatch_source_cancel(downimageTimer);
}

-(void)stratTimerflushThumb
{
    //定时器
    self.startflag = YES;
    flushThumb = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
    dispatch_source_set_timer(flushThumb, DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC,0.0);
    dispatch_source_set_event_handler(flushThumb, ^{
        //下载数据
        //[self getUrlImage:self.templeted];
        PostNoticeObserver(NoticeKey_flushThumb,nil);
    });
    dispatch_resume(flushThumb);
}
-(void)stopTimerflushThumb
{
    if(self.startflag){
    self.startflag = NO;
    dispatch_source_cancel(flushThumb);
    }
}

-(void)downCallBackData:(NSString *)templeted CallBack:(void (^)(UIImage *image))callBack
{
    self.templeted = templeted;
    self.downDroback = callBack;
}
-(void)getUrlImage:(NSString *)templated
{
  //  WeakSelf;
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@.png",kBaseUrl,@"player_image",templated];
    NSString *imagePath = [NSString stringWithFormat:@"%@%@_tmp.png",PATH,templated];
    
    NSString *imagePath_new = [NSString stringWithFormat:@"%@%@.png",PATH,templated];
    
    __block UIImage *image = nil;
    //后台取数据
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            AFHTTPRequestOperation *op = [Network_Operation downloadOperation_Url:url FilePath:imagePath];
            [op start];
            [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                //下载成功 压缩图片
            //if(image){
                @try {
                    image = [UIImage imageWithContentsOfFile:imagePath];
                }
                @catch (NSException *exception) {
                    image = nil;
                }
                @finally {
                  //  image = nil;
                }
              //  }
                if(!image){
                    NSFileManager *file = [NSFileManager defaultManager];
                    NSError *errer = nil;
                    if([file removeItemAtPath:imagePath error:&errer]){
                        NSLog(@"success");
                    }
                    else{
                        NSLog(@"file");
                    }
                }
                else{
                //图片的压缩
//                NSData *imageData = UIImageJPEGRepresentation(image, 0.0001);
                NSData *imageData = UIImagePNGRepresentation(image);
                    //插入二级缓存
                [imageData writeToFile:imagePath_new atomically:YES];
                image = [UIImage imageWithContentsOfFile:imagePath_new];
                NSFileManager *file = [NSFileManager defaultManager];
                NSError *errer = nil;
                if([file removeItemAtPath:imagePath error:&errer]){
                    NSLog(@"success");
                    }
                    else{
                        NSLog(@"file");
                    }
                }
//                NSDictionary *tmpdic = @{imagePath:image};
//                               [[[DownloadImage sharedInstance] CacheImageArr] enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
//                    if(dic[imagePath]){
//                        dic = tmpdic;
//                        wself.isExist = YES;
//                    }
//                }];
//                if(!self.isExist){
//                    if([[[DownloadImage sharedInstance] CacheImageArr] count] >= ARRMAX){
//                        [[[DownloadImage sharedInstance] CacheImageArr] insertObject:tmpdic atIndex:ARRMAX - 1];
//                    }
//                    else{
//                        [[[DownloadImage sharedInstance] CacheImageArr] addObject:tmpdic];
//                    }
//                    self.isExist = NO;
//                }
                if([self.templeted isEqualToString:templated])
                self.downDroback(image);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSFileManager *file = [NSFileManager defaultManager];
                NSError *errer = nil;
                if([file removeItemAtPath:imagePath error:&errer]){
                    NSLog(@"success");
                }
                else{
                    NSLog(@"file");
                }
 
            }];
        });
}

- (void)getUrlThumbImage:(NSString *)templated {
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@.png",kBaseUrl,@"player_image",templated];
    NSString *imagePath = [NSString stringWithFormat:@"%@%@_thumb.png",PATH,templated];
    __block UIImage *image = nil;
    //后台取数据
    AFHTTPRequestOperation *op = [Network_Operation downloadOperation_Url:url FilePath:imagePath];
    [op start];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        //下载成功 压缩图片
        @try {
            image = [UIImage imageWithContentsOfFile:imagePath];
        }
        @catch (NSException *exception) {
            image = nil;
        }
        @finally {
        }
        if(!image){
            NSFileManager *file = [NSFileManager defaultManager];
            NSError *errer = nil;
            if([file removeItemAtPath:imagePath error:&errer]){
                NSLog(@"success");
            }
            else{
                NSLog(@"file");
            }
        }
        else{
            NSData *imageData = UIImagePNGRepresentation(image);
            //插入二级缓存
            [imageData writeToFile:imagePath atomically:YES];
            image = [UIImage imageWithContentsOfFile:imagePath];
            NSFileManager *file = [NSFileManager defaultManager];
            NSError *errer = nil;
            if([file removeItemAtPath:imagePath error:&errer]){
                NSLog(@"success");
            }
            else{
                NSLog(@"file");
            }
        }
//        if([self.templeted isEqualToString:templated]){
//            self.downDroback(image);
//        }
        PostNoticeObserver(NoticeKey_flushThumb,image);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSFileManager *file = [NSFileManager defaultManager];
        NSError *errer = nil;
        if([file removeItemAtPath:imagePath error:&errer]){
            NSLog(@"success");
        }
        else{
            NSLog(@"file");
        }
    }];
}

@end
